package edu.yuhf.web.servlet;

import com.alibaba.fastjson.JSON;
import edu.yuhf.domain.Ad;
import edu.yuhf.service.AdServiceImpl;
import edu.yuhf.service.iface.AdService;
import edu.yuhf.utils.WebUtils;
import lombok.extern.log4j.Log4j;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Log4j
@WebServlet("/ad/*")
public class AdServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        AdService adService= new AdServiceImpl();

        String[] params = WebUtils.getPath(req);

        PrintWriter out = resp.getWriter();
        Map<String,Object> map= new HashMap<>();
        switch (params[1]){
            case "getProvince": {
                List<Ad> list = adService.getProvinces();
                map.put("result", "ok");
                map.put("provinces", list);
                break;
            }
            case "getCity": {
                String currentProvinceCode = params[2];
                List<Ad> list = adService.getCities(currentProvinceCode);
                map.put("result", "ok");
                map.put("cities", list);
                break;
            }
        }

        out.println(JSON.toJSONString(map));
        out.flush();
        out.close();
    }
}
